setLanguageText('label', '标签');
setLanguageText('create label', '添加标签');
setLanguageText('<red>label already exists</red>', '<red>相同标签已存在</red>');

function LabelWidget(elem, value, filter){
	elem = $.pack(elem);

	var self = this;
	var labels = [];
	var imgcss = "style='width:8px;height:8px;margin-left:4px;display:inline-block;cursor:pointer;'";
	var spancss = "style='margin:0px 2px 4px 2px;padding:4px;border-radius:2px;display:inline-block;border:1px solid #AAA;'";

	if (filter == null) filter = isFileName;

	function addItem(){
		let data = {
			model: {label: ''},
			title: [translate('label')],
			style: [{size: 16, minlength: 1, maxlength: 64}]
		};

		let dialog = showToastDialog(data, translate('create label'), function(flag){
			if (flag){
				if (!self.add(data.model.label)){
					dialog.title(translate('<red>label already exists</red>'));
					return false;
				}
			}
		});

		$.pack(dialog.label).change(function(){
			if (!filter($(this).val())) $(this).val('');
		}).focus(function(){
			dialog.title(translate('create label'));
		});
	}

	elem.append("<span " + spancss + "><red style='padding:0px 4px;cursor:pointer'>+</red></span>").children('span').click(function(){
		addItem(this);
	});

	this.add = function(text){
		if (labels.indexOf(text) >= 0) return false;
		var msg = "<span " + spancss + "><green>" + text + "</green><img " + imgcss + " src='/res/img/cross.png'></img></span>";
		elem.children('span:last').before(msg).prev().children('img').click(function(){
			var name = $(this).text();
			$(this).parent().remove();
			labels = labels.filter(item => item == name);
		});
		labels.push(text);
		return true;
	}

	this.clear = function() {
		elem.find('img').click();
	}

	this.val = function(value){
		if (value == null) return labels.join(',');
		if (value == '') self.clear();
		let arr = value.split(',');
		for (let i = 0; i < arr.length; i++){
			if (arr[i].length > 0) self.add(arr[i]);
		}
		return self;
	}

	this.val(value);
}